from django.shortcuts import render
import json,re,random,io,sys,requests,time

from django.views import View
from django.http import JsonResponse,QueryDict,HttpResponse
from django.views.decorators.csrf import csrf_exempt

from py2neo import Graph,Node,Relationship
graph = Graph(host='localhost',auth=('neo4j','123'))

##################课程==================================
# Create your views here.
@csrf_exempt
def findKeCheng(request):
    global graph
    # sql = eval(request.body.decode()).get('sql')
    typePre = eval(request.body.decode()).get('typePre')
    inputPre = eval(request.body.decode()).get('inputPre')
    typeRel = eval(request.body.decode()).get('typeRel')
    typeNext = eval(request.body.decode()).get('typeNext')
    inputNext = eval(request.body.decode()).get('inputNext')

    if typePre == '' or typeNext == '':
        return JsonResponse({"status":"error","success":False})
    else:
        try:
            sql = "match (a:"+typePre+") -[b:"+typeRel+"] ->(c:"+typeNext+") where a.name  =~'.*" + inputPre + ".*' and c.name  =~'.*" + inputNext + ".*'  return a,b,c"
            nodes_source = graph.run(sql).data()
            return JsonResponse({"status": "ok","success": True,"data":nodes_source})
        except Exception as ex:
            print(ex)
            return JsonResponse({"status": "ok","success": False,"data":ex})

@csrf_exempt
def findBySql(request):
    global graph
    sql = eval(request.body.decode()).get('sql')
    if sql == '':
        return JsonResponse({"status":"error","success":False})
    else:
        try:
            nodes_source = graph.run(sql).data()
            return JsonResponse({"status": "ok","success": True,"data":nodes_source})
        except Exception as ex:
            print(ex)
            return JsonResponse({"status": "ok","success": False,"data":ex})

##################课程 end==================================


##################爬虫pois 加油站、充电桩 ==================================
### 爬虫代码：myUtils/baiduPoi.py
### 前端代码：mapbox-example/spider_leaflet_neo4j_pois
@csrf_exempt
def pois_getAll(request):
    global graph
    sql1 = "MATCH (a:Jiayouzhan)-[:Belongto]->(b:Qu) return a,b.name as area"
    sql2 = "MATCH (a:Chongdianzhuang)-[:Belongto]->(b:Qu) return a,b.name as area"
    try:
        nodes_source1 = graph.run(sql1).data()
        nodes_source2 = graph.run(sql2).data()
        result = []
        result.append(nodes_source1)
        result.append(nodes_source2)
        return JsonResponse({"status": "ok", "success": True, "data": result})
    except Exception as ex:
        print(ex)
        return JsonResponse({"status": "ok", "success": False, "data": ex})
